<?php

namespace ApiWF\Controller;

use Common\Controller\AliPush;
use Common\Controller\ApibaseController;

class MessageController extends ApibaseController
{

    /**
     * @param $title 消息标题
     * @param $body 消息内容
     * @param $image 消息图片
     * @param $mg_type 消息类型
     * @param $item_id 消息id
     */
    private function insertAllUserMessageData($title,$body,$image,$mg_type,$item_id,$display_type,$obj_type,$act_start_time=null,$act_end_time=null,$merch_logo=null,$merch_name=null,$merch_floor_name=null,$merch_category_name=null)
    {
        $allUids = M('Users')->where(['user_type'=>2])->field('id')->select();
        $uidArray = array_column($allUids,'id');

        $dataList = [];
        foreach ($uidArray as $uid){
            $dataList[] = [
                'uid'=>$uid,
                'message_type_id'=>$mg_type,
                'title'=>$title,
                'content'=>$body,
                'image'=>$image,
                'create_time'=>date('Y-m-d H:i:s'),
                'send_time'=>date('Y-m-d H:i:s'),
                'obj_id'=>$item_id,
                'act_start_time'=>$act_start_time,
                'act_end_time'=>$act_end_time,
                'display_type'=>$display_type,
                'obj_type'=>$obj_type,
                'merch_logo'=>$merch_logo,
                'merch_name'=>$merch_name,
                'merch_floor_name'=>$merch_floor_name,
                'merch_category_name'=>$merch_category_name,
            ];
        }
        M('UserMessages')->addAll($dataList);
    }

    /**
     * 管理后台调用push 全部用户消息
     */
    public function pushAllUserNotice()
    {

        $mg_id = I('mg_id',0,'intval');
        $mg_type = I('mg_type',0,'intval');

        $title = null;
        $body = null;
        if($mg_type === 1){
            //判断是否是新手任务
            $is_rookie_task = M('ActivityRelationships')->where(['act_id'=>$mg_id,'cate_id'=>3])->find();

            //活动相关
            $item = M('Activity')->where(['id'=>$mg_id])->find();
            $title_push = empty($is_rookie_task) ? '活动推荐' : '新手任务';
            $body_push = $item['act_title'];//act_description
            $body = $item['act_description'];
            $image = qiniu_mirror_image_url_act($item);
            $item_id = $item['id'];
            $act_start_time = $item['start_time'];
            $act_end_time = $item['end_time'];

            //全部用户message
            $display_type = 1;
            $obj_type = $is_rookie_task ? 'task':'activity';//打开详情显示的类型
            $this->insertAllUserMessageData($body_push,$body,$image,$mg_type,$item_id,$display_type,$obj_type,$act_start_time,$act_end_time);
        }
        else if($mg_type === 2){
            //商品
            $item = M('MerchGoods')->where(['id'=>$mg_id])->find();
            $title_push = '商品推荐';
            $body_push = $item['goods_name'];
            $body = $item['goods_description'];

            $image = qiniu_mirror_image_url_merch_good($item);
            $item_id = $item['id'];
            //全部用户message data
            $display_type = 8;
            $obj_type = 'good';

            $mid = $item['mid'];
            $merchInfo = D('MerchView')->where(['Merch.id'=>intval($mid)])->find();
            $merch_name = $merchInfo['merch_name'];
            $merch_logo = qiniu_mirror_image_url_merchant($merchInfo);
            $merch_logo = $merch_logo['avatar'];
            $merch_floor_name = $merchInfo['floor_name'];
            $merch_category_name = $merchInfo['category_name'];


            $this->insertAllUserMessageData($body_push,$body,$image,$mg_type,$item_id,$display_type,$obj_type,null,null,$merch_logo,$merch_name,$merch_floor_name,$merch_category_name);
        }
        else if($mg_type === 3){
            //资讯 商场公告
            $item = M('Posts')->where(['id'=>$mg_id])->find();
            $title_push = '商场资讯';
            $body_push = $item['post_title'];
            $body = $item['post_excerpt'];

            $image = qiniu_mirror_image_url_post($item);
            $item_id = $item['id'];
            $display_type = 10;
            $obj_type = 'post';

            $this->insertAllUserMessageData($body_push,$body,$image,$mg_type,$item_id,$display_type,$obj_type);

        }
        else if($mg_type === 4){
            //优惠券
            $item = M('Coupon')->where(['id'=>$mg_id])->find();
            htmlStringToPlainStirngArray($item,'coupon_description');
            $title_push = '新优惠券';
            $body_push = $item['coupon_title'];
            $body = $item['coupon_description'];

            $image = qiniu_mirror_image_url_coupon($item);
            $item_id = $item['id'];
            //全部用户message data
            $display_type = 4;
            $obj_type = 'coupon';
            $this->insertAllUserMessageData($body_push,$body,$image,$mg_type,$item_id,$display_type,$obj_type);

        }
        else if($mg_type === 5) {
            //商户
            $item = M('Merch')->where(['id'=>$mg_id])->find();
            $title_push = '商户推荐';
            $body_push = $item['merch_name'];
            $body = $item['merch_description'];

            $image = qiniu_mirror_image_url_merchant($item);
            $image = $image['thumb'];
            $item_id = $item['id'];
            $display_type = 9;
            $obj_type = 'merch';
            $this->insertAllUserMessageData($body_push,$body,$image,$mg_type,$item_id,$display_type,$obj_type);
        }



        else {
            $this->error('mg_type 未知');
        }

        $pusher = new AliPush();

        //读取延迟推送配置
        $second = D('Push')->order('id')->find();
        $second = $second['pushtime'];
        $sendTimeString = "+{$second} second";

        $rest = $pusher->pushNotice($title_push,$body_push,null,compact('mg_id','mg_type'),$sendTimeString);
        if($rest){
            $this->success();
        }
    }

    /**
     * 获取消息分类
     */
    public function index(){
        $uid = $this->parseTokenUID();
        $types = [
            ['message_type'=>1,'title'=>'活动推荐','icon'=>''],
            ['message_type'=>2,'title'=>'新品到店','icon'=>''],
            ['message_type'=>3,'title'=>'商场公告','icon'=>''],
            ['message_type'=>4,'title'=>'我的资产','icon'=>''],
            ['message_type'=>5,'title'=>'关注提醒','icon'=>''],
        ];
        foreach ($types as $key=>$vo){
            $where = [
                'message_type_id'=>$vo['message_type'],
                'uid'=>$uid,//uid=0代表是公告
                'send_time'=>['LT',date('Y-m-d H:i:s')],
            ];
            $msg = D('UserMessages')->field('send_time,title,content')->where($where)->order('send_time desc')->find();
            if(empty($msg)){
                unset($types[$key]);
                continue;
            }

            $where['is_read'] = 0;
            $messages_count = D('UserMessages')->field('send_time,title')->where($where)->Count();
            $types[$key]['message_unread'] = intval($messages_count);


            $message_time = $msg['send_time'];
            $types[$key]['message_time'] = empty($msg)? '':$message_time;

            if($vo['message_type'] == 4){
                $message_content = $msg['content'];
            }elseif($vo['message_type'] == 5){
                $message_content = $msg['content'];
            }else {
                $message_content = $msg['title'];
            }
            if(empty($message_content)){
                $types[$key]['message_content'] = '';
            }else {
                $types[$key]['message_content'] = substr($message_content,0,8).'...';
            }

            $types[$key]['message_content'] = empty($message_content)? '':$message_content;
        }
        $data = [];
        foreach ($types as $key=>$vo){
            $data[] = $vo;
        }


        $this->jsonReturn2($data);
    }

    /**
     * 分类消息列表
     */
    public function typeMessages(){
       /*
        display_type:说明

        1:活动-系统通知
        2:活动-开始提醒
        3:活动-结束提醒

        4:优惠券-系统通知
        5:优惠券-到期提醒
        6:优惠券-可用提醒

        7:积分-变动提醒
        8:商品-系统通知
        9:商铺-系统通知
        10:资讯-系统通知/商场公告
        */
        $uid = $this->parseTokenUID();
        $message_type_id = I('message_type_id','0','intval');

        $uid = I('uid',$uid);
        //标记类别消息已读

        $where = [
            'message_type_id'=>$message_type_id,
            'uid'=>$uid,//uid=0代表是公告
            //'send_time'=>['LT',date('Y-m-d H:i:s')],
            '_string'=>'UNIX_TIMESTAMP() > UNIX_TIMESTAMP(send_time)',
        ];

        $order = 'is_read,send_time desc';
        $model = M('UserMessages');
        //标记类别消息已读
        $model->where($where)->save(['is_read'=>1]);
        $data = $this->pageHelper($model,$where,$order);

        $list = $data['list'];

        $data['list'] = $list;
        $this->jsonReturn2($data);
    }

    /**
     * 消息详情
     */
    public function messageDetail(){

        $uid = $this->parseTokenUID();
        $message_id = I('mg_id',0,'intval');
        $message_type_id = I('mg_type',0,'intval');

        $where = [
            'id'=>$message_id,
            'uid'=>$uid,
            'message_type_id'=>$message_type_id,
        ];
        $order = 'send_time desc';

        //标记已读
        D('UserMessages')->where($where)->save([['is_read'=>1]]);

        $msg = D('UserMessages')->where($where)->order($order)->find();

        $this->jsonReturn($msg);
    }
    /**
     * 标记消息 删除
     */
    public function markMessage()
    {
        $token = I('token');
        if(empty($token)){
            $this->error('token为空,请登录!');
        }
        $uid = $this->parseTokenUID();
        $mg_id =  I('message_id', 0, 'intval');
        $mg_type = I('mg_type', 0, 'intval');

        //转换到 obj_type
        if($mg_type === 1){
            $is_rookie_task = M('ActivityRelationships')->where(['act_id'=>$mg_id,'cate_id'=>3])->find();
            $obj_type = $is_rookie_task ? 'task':'activity';//打开详情显示的类型
        }else if($mg_type === 2) {
            $obj_type = 'good';
        }else if($mg_type === 3) {
            $obj_type = 'post';
        }else if($mg_type === 4){
            $obj_type = 'coupon';
        }else if($mg_type === 5){
            $obj_type = 'merch';
        }

        $where = [
            'obj_id' => $mg_id,
            'obj_type' => $obj_type,
            'uid'=>$uid,
        ];

        $type = I('type', 0, 'intval');
        if ($type === 1) {
            //标记已读

            $res = D('UserMessages')->where($where)->save(['is_read' => 1]);

            if ($res) {
                $this->success('消息已读');
            } else {
                $this->error('标记已读失败');
            }
        }

        if ($type === 2) {


            $res = D('UserMessages')->where($where)->delete();
            if ($res) {
                $this->success('删除成功');
            } else {
                $this->error('已经被删除');
            }
        }
    }



}



